/*
 * @Author: g05047
 * @Date: 2021-07-28 09:57:18
 * @LastEditors: g05047
 * @LastEditTime: 2022-02-21 19:24:12
 * @Description: file content
 */
import axios from 'axios';
import { Message, Loading } from 'element-ui';
import { timestamp } from "./token"
// import store from '@/store';
// console.log(store);

import { getToken } from '@/utils/auth';
const service = axios.create({
  timeout: 60000, // request timeout
});
let loadingState = null
// request interceptor
service.interceptors.request.use(
  config => {
    // Do something before request is sent
    // if (getToken()) {
    //   // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
    //   // config.headers['X-Token'] = getToken()
    //   config.headers.Authorization = getToken();
    // }


    //  let timestamp= sessionStorage.getItem('timestamp')
    //   if(timestamp){

    //   }
    config.headers.timestamp = timestamp();
    config.headers.id = sessionStorage.getItem('userId') || ''
    config.headers.code = sessionStorage.getItem('token') || ''
    if (config.loading && !loadingState) {
      loadingState = Loading.service({ fullscreen: true, background: 'rgba(0, 0, 0, 0.7)', spinner: 'el-icon-loading', text: '加载中...' });
    }
    return config;
  },
  error => {
    // Do something with request error
    console.log(error); // for debug
    Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  // response => response,
  /**
   * 下面的注释为通过在response里，自定义code来标示请求状态
   * 当code返回如下情况则说明权限有问题，登出并返回到登录页
   * 如想通过 xmlhttprequest 来状态码标识 逻辑可写在下面error中
   * 以下代码均为样例，请结合自生需求加以修改，若不需要，则可删除
   */
  response => {
    // return response.data;
    const res = response.data;
    if (response.config.loading) {
      loadingState && loadingState.close()
      loadingState = null
    }
    // console.log(response.config);
    if (res.code == 408) {
      sessionStorage.removeItem("userId")
      sessionStorage.removeItem('token')
      location.href = "#/401"
    } else if (response.config.isAuth) {
      return res
    } else if (res.code !== 200) {
      Message.closeAll()
      Message({
        message: res.msg || '网络错误',
        type: 'error',
        duration: 5 * 1000,
      });

      // 50008:非法的token; 50012:其他客户端登录了;  50014:Token 过期了;
      // if (res.code == 400 || res.code === 50012 || res.code === 50014) {
      //   // 请自行在引入 MessageBox
      //   // import { Message, MessageBox } from 'element-ui'
      //   MessageBox.confirm(
      //     '你已被登出/或网络异常，可以取消继续留在该页面，或者重新登录',
      //     '确定登出',
      //     {
      //       confirmButtonText: '重新登录',
      //       cancelButtonText: '取消',
      //       type: 'warning',
      //     }
      //   )
      //     .then(() => {
      //       store.dispatch('FedLogOut').then(() => {
      //         location.reload(); // 为了重新实例化vue-router对象 避免bug
      //       });
      //     })
      //     .catch(res => {
      //       console.log(res);
      //     });
      // }
      return Promise.reject(res);
      // return res
    } else {
      return res
    }
  },
  error => {
    loadingState && loadingState.close()
    loadingState = null
    Message.closeAll()
    Message({
      message: showStatus(error.response && error.response.status || 504),
      type: 'error',
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);
const showStatus = (status) => {
  let message = ''
  switch (status) {
    case 400:
      message = '请求错误(400)'
      break
    case 401:
      message = '未授权，请重新登录(401)'
      break
    case 403:
      message = '无访问或操作权限(403)'
      break
    case 404:
      message = '请求出错(404),未找到文件'
      break
    case 408:
      message = '请求超时(408)'
      break
    case 500:
      message = '后台异常(500)'
      break
    case 501:
      message = '服务未实现(501)'
      break
    case 502:
      message = '网络错误(502)'
      break
    case 503:
      message = '服务不可用(503)'
      break
    case 504:
      message = '网络超时(504)'
      break
    case 505:
      message = 'HTTP版本不受支持(505)'
      break
    default:
      message = `连接出错(${status})!`
  }
  return `${message}，请检查网络或联系管理员！`
}
export default service;
